package com.brower.project.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VB : ViewDataBinding, VM : BaseViewModel> : Fragment() {
    var mBinding: VB? = null
    lateinit var mViewModel: VM
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = DataBindingUtil.inflate(inflater, layoutId(), container, false)
        mViewModel = ViewModelProvider(this).get(viewModelClass())
        val variable = getVariable()
        if (variable?.size ?: 0 > 0) {
            for (i in variable!!){
                mBinding?.setVariable(i.key, i.value)
            }
        }
        initView()
        observerListener()
        return mBinding!!.root
    }

    open fun getVariable(): HashMap<Int, Any?>? = null

    abstract fun layoutId(): Int
    private fun viewModelClass(): Class<VM> {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[1]
            return tp as Class<VM>
        }
        throw Throwable("请添加ViewModel")
    }

    open fun initView() {}
    open fun observerListener() {}

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

    open fun <T> addObserver(data: LiveData<T>, observer: Observer<T>) {
        data.observe(viewLifecycleOwner, observer)
    }

}